package web.selvlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import pojo.Emp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/empServlet")
public class EmpServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理中文乱码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        //获取request域中存储的数据
        List<Emp> emps = (List<Emp>) req.getAttribute("emps");
//        resp.getWriter().print(emps);
        //创建ObjectMapper对象 作用：java对象转json数据格式
//        ObjectMapper om = new ObjectMapper();
//        String s = om.writeValueAsString(emps);
        PrintWriter pw = resp.getWriter();
//        pw.print(s);
//        pw.close();
        pw.println("<!DOCTYPE html>");
        pw.println("<html>");
        pw.println("<head>");
        pw.println("<title>员工信息表</title>");
        pw.println("<style>");
        pw.println("table { width: 100%; border-collapse: collapse; margin: 20px auto; }");
        pw.println("th, td { border: 1px solid #000; padding: 8px; text-align: center; }");
        pw.println("th { background-color: #f2f2f2; }");
        pw.println("</style>");
        pw.println("</head>");
        pw.println("<body>");
        pw.println("<h2 style='text-align: center;'>员工信息表</h2>");
        pw.println("<table>");
        pw.println("<tr>");
        pw.println("<th>员工编号</th>");
        pw.println("<th>员工姓名</th>");
        pw.println("<th>职位</th>");
        pw.println("<th>上级编号</th>");
        pw.println("<th>入职日期</th>");
        pw.println("<th>工资</th>");
        pw.println("<th>佣金</th>");
        pw.println("<th>部门编号</th>");
        pw.println("<th>操作</th>");
        pw.println("</tr>");

        // 循环输出表格数据
        for (Emp emp : emps) {
            pw.println("<tr>");
            pw.println("<td>" + emp.getEmpno() + "</td>");
            pw.println("<td>" + emp.getEname() + "</td>");
            pw.println("<td>" + (emp.getJob() == null ? "无" : emp.getJob()) + "</td>");
            pw.println("<td>" + emp.getMgr() + "</td>");
            pw.println("<td>" + emp.getHiredate() + "</td>");
            pw.println("<td>" + emp.getSalary() + "</td>");
            pw.println("<td>" + emp.getComm() + "</td>");
            pw.println("<td>" + emp.getDeptno() + "</td>");
            pw.println("<td><a href='#'>删除</a>&nbsp;<a href='#'>修改</a></td>");
            pw.println("</tr>");
        }

        pw.println("</table>");
        pw.println("</body>");
        pw.println("</html>");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
